package com.teangtang.fly.service;

import com.teangtang.fly.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

import javax.annotation.Resource;

@Service
public class loginService {

    @Value("${spring.aliyun.sms.access-key-id}")
    private String accessKeyId;

    @Value("${spring.aliyun.sms.access-key-secret}")
    private String accessKeySecret;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AdminRepository adminRepository;
    public boolean adminLogin(String username, String password) {
        return adminRepository.existsByUsernameAndPassword(username, password);
    }

    // 发送短信验证码
    public SendSmsResponse sendSms(String phoneNumber, String signName, String templateCode, String templateParam) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setTemplateParam(templateParam);

        try {
            return client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 验证验证码
    public boolean verifyCode(String phoneNumber, String inputCode) {
        String storedCode = stringRedisTemplate.opsForValue().get(phoneNumber);
        if (storedCode != null && storedCode.equals(inputCode)) {
            // 验证成功后删除验证码，防止重复使用
            stringRedisTemplate.delete(phoneNumber);
            return true;
        }
        return false;
    }

}
